/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 版本: 苏州公安统一用户管理平台1.0
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名:SessionInterceptor.java
 * <p>
 * 类产生时间: 2012-5-23 下午4:27:57
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 苏州公安统一用户管理平台
 * <p>
 * 所在部门: 电信/国土——技术二部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.interceptor;

import com.oceansoft.mobile.econsole.common.constant.Constant;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;

/**
 * 普通用户后台管理会话合法性拦截器
 *
 * @author chenw
 */
public class SessionInterceptor implements Filter {

    private ArrayList<String> safeUrl;
    private PathMatcher matcher;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object obj = request.getSession().getAttribute(Constant.SESSION_USER);
        String url = request.getRequestURI().toLowerCase();
        String header = request.getHeader("x-requested-with");
        System.out.println("Access URL=>" + url);
        boolean isAjax = (null != header && header.equalsIgnoreCase("XMLHttpRequest")) || url.endsWith(".json") || url.endsWith(".xml");
        if (null != obj || isSafeUrl(url)) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            if (isAjax) {
                response.setContentType("application/json;charset=UTF-8");
                Writer writer = response.getWriter();
                writer.write("{\"status\":0,\"code\":259,\"msg\":\"会话超时！\"}");
                writer.flush();
                writer.close();
            } else {
                request.getRequestDispatcher("/profile/login").forward(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String str = config.getInitParameter("excludeUrl");
        safeUrl = new ArrayList<String>();
        if (StringUtils.hasText(str) && str.split(",").length > 0) {
            matcher = new AntPathMatcher();
            Collections.addAll(safeUrl, str.split(","));
        }
    }

    @Override
    public void destroy() {
        safeUrl.clear();
        safeUrl = null;
    }

    /**
     * 判断是否为安全URL(白名单)
     *
     * @param url 访问URL
     * @return boolean true安全 反之返回false
     */
    private boolean isSafeUrl(String url) {
        for (String item : safeUrl) {
            if (matcher.match(item, url)) {
                return true;
            }
        }
        return false;
    }
}
